package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.list.repository.GoodsRepository;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/5/17 14:09
 * @Version 1.0
 */
@Service
public class SearchServiceImpl implements SearchService  {

    //  将数据保存到es; 使用es 客户端.
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public void upperGoods(Long skuId) {
        //  创建实体类对象
        Goods goods = new Goods();
        //  给实体类赋值
        CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //  获取商品数据
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            goods.setId(skuId);
            goods.setTitle(skuInfo.getSkuName());
            //  有可能不是最新的价格
            // goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setPrice(productFeignClient.getSkuPrice(skuId).doubleValue());
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setCreateTime(new Date());
            return skuInfo;
        });

        //  获取品牌数据：
        CompletableFuture<Void> tmCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            BaseTrademark tradeMark = productFeignClient.getTradeMark(skuInfo.getTmId());
            goods.setTmId(tradeMark.getId());
            goods.setTmName(tradeMark.getTmName());
            goods.setTmLogoUrl(tradeMark.getLogoUrl());
        });
        //  获取分类数据
        CompletableFuture<Void> categoryCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory3Id(categoryView.getCategory3Id());

            goods.setCategory1Name(categoryView.getCategory1Name());
            goods.setCategory2Name(categoryView.getCategory2Name());
            goods.setCategory3Name(categoryView.getCategory3Name());

        });

        //  需要远程调用：
        CompletableFuture<Void> attrCompletableFuture = CompletableFuture.runAsync(() -> {
            //  获取到平台属性+平台属性值
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
            //  拉姆达表达式
            List<SearchAttr> searchAttrList = attrList.stream().map(baseAttrInfo -> {
                //  创建一个SearchAttr 对象
                SearchAttr searchAttr = new SearchAttr();
                //  获取平台属性数据并赋值
                searchAttr.setAttrId(baseAttrInfo.getId());
                searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
                searchAttr.setAttrName(baseAttrInfo.getAttrName());
                return searchAttr;
            }).collect(Collectors.toList());
            //  赋值平台属性 List<SearchAttr> attrs
            goods.setAttrs(searchAttrList);
        });

        //  多任务组合
        CompletableFuture.allOf(
                skuInfoCompletableFuture,
                categoryCompletableFuture,
                attrCompletableFuture,
                tmCompletableFuture
        ).join();
        //  保存数据
        this.goodsRepository.save(goods);
    }

    @Override
    public void lowerGoods(Long skuId) {
        //  删除
        this.goodsRepository.deleteById(skuId);
    }

    @Override
    public void incrHotScore(Long skuId) {
        //  执行 zincrby hotscore 1 25
        String hotKey = "hotScore";
        Double count = this.redisTemplate.opsForZSet().incrementScore(hotKey, "skuId:" + skuId, 1);
        //  判断
        if (count%10==0){
            //  更新es
            Optional<Goods> optionalGoods = this.goodsRepository.findById(skuId);
            Goods goods = optionalGoods.get();
            goods.setHotScore(count.longValue());
            this.goodsRepository.save(goods);
        }
    }

    @Override
    public SearchResponseVo search(SearchParam searchParam) {
        //  1.  生成dsl语句
        SearchRequest searchRequest = this.queryBuildDsl(searchParam);
        //  2.  调用api 执行dsl 语句
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  3.  返回结果---封装成 SearchResponseVo 这个对象
        SearchResponseVo searchResponseVo = this.parseResult(searchResponse);
        /*
        private Integer pageSize;//每页显示的内容
        private Integer pageNo;//当前页面
        private Long totalPages;//总页数
         */
        searchResponseVo.setPageSize(searchParam.getPageSize());
        searchResponseVo.setPageNo(searchParam.getPageNo());
        //  总页数： 10 3 4  |  9 3 3
        //        Long totalPages = searchResponseVo.getTotal()%searchParam.getPageSize()==0?searchResponseVo.getTotal()/searchParam.getPageSize():searchResponseVo.getTotal()/searchParam.getPageSize()+1
        Long totalPages = (searchResponseVo.getTotal()+searchParam.getPageSize()-1)/searchParam.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        //  4.  返回数据
        return searchResponseVo;
    }

    /**
     * 封装返回数据
     * @param searchResponse
     * @return
     */
    private SearchResponseVo parseResult(SearchResponse searchResponse) {
        //  创建一个对象
        SearchResponseVo searchResponseVo = new SearchResponseVo();
        /*
        本质就是给以下属性进行赋值.
        private List<SearchResponseTmVo> trademarkList;
        private List<SearchResponseAttrVo> attrsList = new ArrayList<>();
        private List<Goods> goodsList = new ArrayList<>();
        private Long total;//总记录数
         */
        //  total 总记录数
        SearchHits hits = searchResponse.getHits();
        searchResponseVo.setTotal(hits.getTotalHits().value);
        //  赋值商品集合列表.
        List<Goods> goodsList = new ArrayList<>();
        //  获取_source节点下的Goods
        SearchHit[] subHits = hits.getHits();
        for (SearchHit subHit : subHits) {
            //  获取的数据是Json格式
            String sourceAsString = subHit.getSourceAsString();
            //  获取goods对象
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            //  判断是否有高亮字段：
            if (subHit.getHighlightFields().get("title")!=null){
                //  获取商品的高亮字段.
                String title = subHit.getHighlightFields().get("title").getFragments()[0].toString();
                goods.setTitle(title);
            }
            //  将对象添加到集合中.
            goodsList.add(goods);
        }
        //  赋值商品集合
        searchResponseVo.setGoodsList(goodsList);

        //  获取品牌集合数据 - 从聚合获取
        Map<String, Aggregation> aggregationMap = searchResponse.getAggregations().asMap();
        ParsedLongTerms tmIdAgg = (ParsedLongTerms) aggregationMap.get("tmIdAgg");
        //  List<SearchResponseTmVo> trademarkList
        List<SearchResponseTmVo> trademarkList = tmIdAgg.getBuckets().stream().map(bucket -> {
            //  创建一个记录品牌的对象
            SearchResponseTmVo searchResponseTmVo = new SearchResponseTmVo();
            //  获取品牌Id 并赋值
            String tmId = bucket.getKeyAsString();
            searchResponseTmVo.setTmId(Long.parseLong(tmId));
            //  获取品牌的名称
            ParsedStringTerms tmNameAgg = bucket.getAggregations().get("tmNameAgg");
            String tmName = tmNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmName(tmName);
            //  获取品牌的LogoUrl
            ParsedStringTerms tmLogoUrlAgg = bucket.getAggregations().get("tmLogoUrlAgg");
            String tmLogoUrl = tmLogoUrlAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmLogoUrl(tmLogoUrl);
            //  返回对象
            return searchResponseTmVo;
        }).collect(Collectors.toList());
        //  赋值品牌集合数据.
        searchResponseVo.setTrademarkList(trademarkList);
        //  获取平台属性集合数据 - 从聚合获取
        ParsedNested attrsAgg = (ParsedNested) aggregationMap.get("attrsAgg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attrIdAgg");
        //  List<SearchResponseAttrVo> attrsList = new ArrayList<>();
        //  获取平台属性数据集合
        List<SearchResponseAttrVo> attrVoList = attrIdAgg.getBuckets().stream().map(bucket -> {
            //  创建平台属性对象
            SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
            //  赋值平台属性Id
            String attrId = bucket.getKeyAsString();
            searchResponseAttrVo.setAttrId(Long.parseLong(attrId));
            //  赋值平台属性名：
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseAttrVo.setAttrName(attrName);
            //  赋值平台属性值：
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            //  stream()。map
            //  List<String> attrValueNameList = attrValueAgg.getBuckets().stream().map(bucket1 -> bucket1.getKeyAsString()).collect(Collectors.toList());
            //  方法引用
            List<String> valueList = attrValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            //  获取到平台属性值集合数据
            searchResponseAttrVo.setAttrValueList(valueList);
            //  返回对象
            return searchResponseAttrVo;
        }).collect(Collectors.toList());
        //  赋值平台属值集合
        searchResponseVo.setAttrsList(attrVoList);

        //  返回数据.
        return searchResponseVo;
    }

    /**
     * 生成searchRequest对象
     * @param searchParam
     * @return
     */
    private SearchRequest queryBuildDsl(SearchParam searchParam) {
        //  创建一个查询器对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //  创建bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //  要判断用户根据什么条件进行了检索. 说明用户是通过分类检索查询的！
        if (!StringUtils.isEmpty(searchParam.getCategory3Id())){
            //  query -- bool -- filter
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",searchParam.getCategory3Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory2Id())){
            //  query -- bool -- filter
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",searchParam.getCategory2Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory1Id())){
            //  query -- bool -- filter
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",searchParam.getCategory1Id()));
        }
        //  用户是根据全文检索查询
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            //  bool -- must -- match
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",searchParam.getKeyword()).operator(Operator.AND));
            //  设置高亮
            //  创建一个高亮对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.preTags("<span style=color:red>");
            highlightBuilder.postTags("</span>");
            //  将设置好的高亮对象放入方法中.
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //  是否又根据品牌Id 进行过滤. trademark=1:小米:url
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            //  要想获取到品牌Id
            String[] split = trademark.split(":");
            if (split!=null && split.length==2){
                //  bool - filter - term
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId",split[0]));
            }
        }

        //  平台属性Id 过滤.
        //  先获取到页面传递的平台属性数据值;
        String[] props = searchParam.getProps();
        if (props!=null && props.length>0){
            //  props=24:128G:机身内存&props=23:4G:运行内存
            //  循环遍历整个数据
            for (String prop : props) {
                //  先进行分割
                String[] split = prop.split(":");
                if (split!=null && split.length==3){
                    //  构建内部查询条件
                    BoolQueryBuilder innerBoolQueryBuilder = QueryBuilders.boolQuery();
                    innerBoolQueryBuilder.must(QueryBuilders.matchQuery("attrs.attrId",split[0]));
                    innerBoolQueryBuilder.must(QueryBuilders.matchQuery("attrs.attrValue",split[1]));
                    //  构建内部数据查询
                    boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs",innerBoolQueryBuilder, ScoreMode.None));
                }
            }
        }
        //  分页：
        int from = (searchParam.getPageNo()-1)*searchParam.getPageSize();
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(searchParam.getPageSize());

        //  排序：
        //  获取到页面排序规则
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)){
            //  order=1:asc order=1:desc  order=2:asc  order=2:desc
            //  进行分割获取数据
            String[] split = order.split(":");
            if (split!=null && split.length==2){
                String field = "";
                switch (split[0]){
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "price";
                        break;
                }
                //  设置排序规则
                searchSourceBuilder.sort(field,"asc".equals(split[1])?SortOrder.ASC:SortOrder.DESC);
            }
        } else {
            //    设置默认排序规则
            searchSourceBuilder.sort("hotScore",SortOrder.DESC);
        }
        //  聚合： 去重+显示
        //  品牌聚合
        searchSourceBuilder.aggregation( AggregationBuilders.terms("tmIdAgg").field("tmId")
                .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl"))
        );
        //  平台属性聚合：
        searchSourceBuilder.aggregation(AggregationBuilders.nested("attrsAgg","attrs")
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))
                )
        );

        //  query -- bool
        searchSourceBuilder.query(boolQueryBuilder);
        //  创建SearchRequest 对象
        //  GET /goods/_search
        SearchRequest searchRequest = new SearchRequest("goods");
        //  设置用户检索的字段
        searchSourceBuilder.fetchSource(new String[] {"id","title", "defaultImg","price"},null);
        searchRequest.source(searchSourceBuilder);
        System.out.println("dsl:\t"+searchSourceBuilder.toString());
        System.out.println("dsl-noToString:\t"+searchSourceBuilder);
        //  返回请求对象
        return searchRequest;
    }
}
